using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using NHibernate;
using System.Collections;

namespace TanashCMS.Business
{
    /// <summary>
    /// Various helper methods for NHibernate
    /// </summary>
    public sealed class Configuration
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static ISessionFactory sessionFactory;

        static Configuration()
        {
            try
            {
                BuildSessionFactory();
            }
            catch (HibernateException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void BuildSessionFactory()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            Hashtable properties = new Hashtable();
            properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver");
            properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2000Dialect");
            properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            properties.Add("hibernate.connection.connection_string", System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
            cfg.SetProperties(properties);

            cfg.AddAssembly("TanashCMS.Business");
            //cfg.Configure();

            sessionFactory = cfg.BuildSessionFactory();
        }

        public static ISession GetCurrentSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;

            if (currentSession == null)
            {
                if (sessionFactory == null)
                    throw new NHibernate.HibernateException("sessionFactory is null!");

                currentSession = sessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
            }

            if (currentSession.IsOpen && !currentSession.IsConnected)
                currentSession.Reconnect();

            return currentSession;
        }

        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;

            if (currentSession == null)
            {
                // No current session
                return;
            }

            currentSession.Close();
            context.Items.Remove(CurrentSessionKey);
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }


    }
}
